package cn.wsn2018.tools.ctrl;

import cn.wsn2018.tools.common.CommonValue;
import cn.wsn2018.tools.model.LoginUser;
import cn.wsn2018.tools.model.MySessionContext;
import cn.wsn2018.tools.model.User;
import cn.wsn2018.tools.service.UserService;
import cn.wsn2018.tools.util.JsonUtil;
import cn.wsn2018.tools.util.LogUtil;
import cn.wsn2018.tools.util.ServletUtil;
import net.sf.json.JSONObject;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;
import java.net.InetAddress;


@RestController
@RequestMapping("/protocol")
public class UserController {
    private static final Logger logger = LoggerFactory.getLogger(UserController.class);

    @Autowired
    private UserService userService;


    @CrossOrigin
    @RequestMapping(value = "/login",method = RequestMethod.POST)
    /**
     * 处理前端登录表单，前端填写用户名密码经过验证之后返回json字符串
     */
    public void login(@RequestParam("username") String username,
                      @RequestParam("password") String password, HttpServletRequest request, HttpServletResponse response)throws Exception{
        //int i=1/0;

        //User user=null;
        //System.out.println(user.getId());

        //int[] arr={1,2,3};
        //System.out.println(arr[3]);

        ServletUtil.getInstance().requestOperating(request);
        String json=userService.dealUserLogin(username,password);
        JSONObject jsonObject = JSONObject.fromObject(json);
        String state = jsonObject.getJSONObject("meta").optString("state");
        if("success".equals(state)){
            //MySessionContext myc= MySessionContext.getInstance();
            String role = jsonObject.getJSONObject("data").optString("role");
            HttpSession session = request.getSession(true);
            session.setAttribute("username",username);
            session.setAttribute("role",role);
            //myc.addSession(session);
            response.setHeader("token",session.getId());
            ServletUtil.getInstance().responseOperating(response, json);
        }else {
            Integer num =  ServletUtil.getFailedNum(username);
            num++;
            if(num>=5){
                if(num>=10){
                    //失败次数大于10 则视为严重
                    LogUtil.produceWarningLogs(username,
                            CommonValue.WARNING_TYPE_0,
                            CommonValue.WARNING_LEVEL_0,
                            CommonValue.LOGINMODULE,
                            ServletUtil.getClientIp(request),
                            CommonValue.WARNING_TYPE_0+":用户名为"+username+"的用户多次登录失败,累积登录失败:"+num+"次");
                }else{
                    LogUtil.produceWarningLogs(username,
                            CommonValue.WARNING_TYPE_0,
                            CommonValue.WARNING_LEVEL_1,
                            CommonValue.LOGINMODULE,
                            ServletUtil.getClientIp(request),
                            CommonValue.WARNING_TYPE_0+":用户名为"+username+"的用户多次登录失败,累积登录失败:"+num+"次");
                }
            }
            ServletUtil.updateFailedNum(username,num);
            ServletUtil.getInstance().responseOperating(response, json);
        }

    }
    @CrossOrigin
    @RequestMapping(value = "/logout",method = RequestMethod.POST)
    /**
     * 退出登录
     */
    public void logout(@RequestParam("token") String token,HttpServletRequest request,HttpServletResponse response)throws Exception{
        MySessionContext myc= MySessionContext.getInstance();
        HttpSession session = myc.getSession(token);
        String myUsername = session.getAttribute("username").toString();
        //myc.delSession(session);
        session.invalidate();
        if(request.getSession(false)==null){
            LogUtil.produceLogs(myUsername,CommonValue.LOGOUT_TYPE,CommonValue.LOGOUT_LOGINFO,CommonValue.SUCCESS);
            String json = JsonUtil.successJson(CommonValue.JSON_LOGOUT_SUCCESS,null,null);
            ServletUtil.getInstance().responseOperating(response, json);
        }else {
            LogUtil.produceLogs(myUsername,CommonValue.LOGOUT_TYPE,CommonValue.LOGOUT_LOGINFO,CommonValue.FAILED);
            String json = JsonUtil.successJson(CommonValue.JSON_LOGOUT_FAILED,null,null);
            ServletUtil.getInstance().responseOperating(response, json);
        }
    }
    @CrossOrigin
    @RequestMapping(value = "/checkLogin",method = RequestMethod.GET)
    /**
     * 确认登录
     */
    public void checkLogin(HttpServletRequest request,HttpServletResponse response)throws Exception{
        String json = JsonUtil.successJson(CommonValue.JSON_LOGIN_ONLINE,null,null);
        ServletUtil.getInstance().responseOperating(response, json);
    }


    @CrossOrigin
    @RequestMapping(value = "/users",method = RequestMethod.POST)
    /**
     * 处理前端添加用户表单，前端填写用户名经过验证之后返回json字符串
     */
    public void createUser(@RequestParam("username") String username,
                           @RequestParam("role") String role,
                           @RequestParam("token") String token, HttpServletRequest request, HttpServletResponse response)throws Exception{
        ServletUtil.getInstance().requestOperating(request);
        MySessionContext myc= MySessionContext.getInstance();
        HttpSession session = myc.getSession(token);
        String myUsername = session.getAttribute("username").toString();
        String myRole = session.getAttribute("role").toString();
        if(CommonValue.ROLE_ADMIN.equals(myRole)){
            String json = userService.dealUserCreate(username,role,myUsername);
            ServletUtil.getInstance().responseOperating(response, json);
        }else {
            LogUtil.produceLogs(myUsername,CommonValue.CREATE_TYPE,CommonValue.CREATE_USER_LOGINFO+username,CommonValue.FAILED);
            String json = JsonUtil.failedJson(CommonValue.JSON_ROLE_ERROR);
            ServletUtil.getInstance().responseOperating(response, json);
        }
    }

    @CrossOrigin
    @RequestMapping(value = "/admin",method = RequestMethod.POST)
    /**
     * 添加管理员
     */
    public void createAdmin(@RequestParam("username") String username,
                           @RequestParam("token") String token, HttpServletRequest request, HttpServletResponse response)throws Exception{
        ServletUtil.getInstance().requestOperating(request);
        if(username!=null&&token!=null&&token.equals("wsnwsn")){
            String json = userService.dealAdminCreate(username);
            ServletUtil.getInstance().responseOperating(response, json);
        }else {
            String json = JsonUtil.failedJson(CommonValue.JSON_ROLE_ERROR);
            ServletUtil.getInstance().responseOperating(response, json);
        }


    }

    @CrossOrigin
    @RequestMapping(value = "/users/username",method = RequestMethod.PUT)
    /**
     * 修改用户密码
     */
    public void updateUser(@RequestParam("username") String username,
                           @RequestParam("formerPassword") String formerPassword,
                           @RequestParam("newPassword") String newPassword,
                           @RequestParam("token") String token, HttpServletRequest request, HttpServletResponse response)throws Exception{
        ServletUtil.getInstance().requestOperating(request);
        MySessionContext myc= MySessionContext.getInstance();
        HttpSession session = myc.getSession(token);
        String myUsername = session.getAttribute("username").toString();
        String json = userService.dealUserUpdate(username,formerPassword,newPassword,myUsername);
        ServletUtil.getInstance().responseOperating(response, json);
    }
    @CrossOrigin
    @RequestMapping(value = "/users/username",method = RequestMethod.GET)
    /**
     * 查询用户详情
     */
    public void findUsers(@RequestParam("username") String username,
                          HttpServletRequest request, HttpServletResponse response)throws Exception{
        ServletUtil.getInstance().requestOperating(request);
        String json = userService.dealOneUserFind(username);
        ServletUtil.getInstance().responseOperating(response, json);
    }

    @CrossOrigin
    @RequestMapping(value = "/users/role",method = RequestMethod.GET)
    /**
     * 按角色查询用户
     */
    public void findUsers(@RequestParam("role") String role,
                          @RequestParam("pageNum") String pageNum,
                          @RequestParam("pageSize")String pageSize,
                          HttpServletRequest request, HttpServletResponse response)throws Exception{
        ServletUtil.getInstance().requestOperating(request);
        String json = userService.dealUsersFindByRole(role,pageNum,pageSize);
        ServletUtil.getInstance().responseOperating(response, json);
    }
    @CrossOrigin
    @RequestMapping(value = "/users",method = RequestMethod.GET)
    /**
     * 查询所有用户
     */
    public void findUsers(@RequestParam("pageNum") String pageNum,
                          @RequestParam("pageSize")String pageSize,
                          HttpServletRequest request, HttpServletResponse response)throws Exception{
        ServletUtil.getInstance().requestOperating(request);
        String json = userService.dealAllUsersFind(pageNum,pageSize);
        ServletUtil.getInstance().responseOperating(response, json);
    }
    @CrossOrigin
    @RequestMapping(value = "/users/username",method = RequestMethod.DELETE)
    /**
     * 删除用户
     */
    public void deleteUser(@RequestParam("username") String username,
                           @RequestParam("token") String token,HttpServletRequest request,HttpServletResponse response)throws Exception{
        ServletUtil.getInstance().requestOperating(request);
        MySessionContext myc= MySessionContext.getInstance();
        HttpSession session = myc.getSession(token);
        String myUsername = session.getAttribute("username").toString();
        String myRole = session.getAttribute("role").toString();
        if(CommonValue.ROLE_ADMIN.equals(myRole)){
            String json = userService.dealUserDelete(username,myUsername);
            ServletUtil.getInstance().responseOperating(response, json);
        }else {
            LogUtil.produceLogs(myUsername,CommonValue.DELETE_TYPE,CommonValue.DELETE_USER_LOGINFO+username,CommonValue.FAILED);
            String json = JsonUtil.failedJson(CommonValue.JSON_ROLE_ERROR);
            ServletUtil.getInstance().responseOperating(response, json);
        }
    }

}
